package cn.lg.soar.system.biz.modules.monitor.client;

import cn.lg.soar.common.model.LogDTO;
import cn.lg.soar.core.annotations.ApiClient;
import cn.lg.soar.core.handler.log.IOperationLogSaveService;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.biz.modules.monitor.entity.OperationLog;
import cn.lg.soar.system.biz.modules.monitor.service.OperationLogService;
import io.swagger.v3.oas.annotations.Hidden;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 简单日志接口
 * @author luguoxiang
 * @date 2021-08-11
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Hidden
@Primary
@ApiClient("boot")
@RestController
@RequestMapping(ModuleConst.CLIENT_PATH + "/log")
public class OperationLogApiClient implements IOperationLogSaveService {

    @Autowired
    private OperationLogService operationLogService;

    /**
     * 保存操作日志到数据库
     * @param logs
     */
    @PostMapping("saveLog")
    @Override
    public void saveLog(@RequestBody Collection<? extends LogDTO> logs) {
        List<OperationLog> list = logs.stream().map(this::toOperationLog).collect(Collectors.toList());
        operationLogService.saveBatch(list);
    }

    private OperationLog toOperationLog(LogDTO source) {
        if (source == null) {
            return null;
        }

        OperationLog target = new OperationLog();

        target.setType(source.getType());
        target.setStartTime(source.getStartTime());
        target.setTenantId(source.getTenantId());
        target.setUserType(source.getUserType());
        target.setUserId(source.getUserId());
        target.setClientType(source.getClientType());
        target.setClientIp(source.getClientIp());
        target.setUserAgent(source.getUserAgent());
        target.setTitle(source.getTitle());
        target.setDuration(source.getDuration());
        target.setTraceId(source.getTraceId());
        target.setPath(source.getPath());
        target.setContent(source.getContent());
        target.setJavaMethod(source.getJavaMethod());
        target.setArgs(source.getArgs());
        target.setResult(source.getResult());
        target.setErrorStack(source.getErrorStack());

        return target;
    }

}
